# -*- coding: UTF-8 -*-
#!/usr/bin/python
import json

def exc(josns):
	if josns.strip()=='':
		return ''
	#print(josns)
	j=json.loads(josns.encode('UTF-8'));
	singleResult=j['singleResult']
	j1=json.loads(singleResult)
	resultsRoots=j1['resultsRoot']
	hiveSql=j1['hiveSql']
	print(hiveSql)
	fromn=hiveSql.find('from')
	if fromn<0:
		fromn=hiveSql.find('FROM')
	wheren=hiveSql.find('where')
	if wheren<0:
		wheren=hiveSql.find('WHERE')
	if wheren<0:
		wheren=hiveSql.find('limit')
	if wheren<0:
		wheren=hiveSql.find('LIMIT')
	tablename=hiveSql[fromn+4:wheren]
	#print(tablename)
	results=resultsRoots[0]['results']
	resultColumns=resultsRoots[1]['resultColumns']
	sql='insert into '+tablename+'('
	for resultColumn in resultColumns:
		sql=sql+resultColumn['dataIndex']+','
	sql=sql[0:len(sql)-1]
	sql=sql+') values'
	#print(sql)
	for result in results:
		sql=sql+'('
		for resultColumn in resultColumns:
			column=resultColumn['dataIndex']
			f=result[column]
			if f is None:
				sql=sql+'null,'
			else:
				sql=sql+'\''+f+'\','
		sql=sql[0:len(sql)-1]
		sql=sql+'),\n'
	return sql
	#print(sql)

f = open('f:/jsop.txt', 'r',encoding='utf8')
f2 = open('f:/jsop.sql', 'w',encoding='utf8')
try:
	for line in f:
		sql=exc(line)
		if sql!='':
			f2.write(sql[0:len(sql)-1])
finally:
    f.close()
    f2.close()
#print(type(resultsRoots[0]['results']))
#print(json.dumps(results))